package com.lzm.ydpt.module.mall.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.basemvp.boby.FormBodys;
import com.byt.framlib.commonwidget.NormalTitleBar;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.byt.framlib.commonwidget.onclicktwo.AntiShake;
import com.byt.framlib.commonwidget.selectordialog.dialog.DialogOnClickListener;
import com.byt.framlib.commonwidget.selectordialog.dialog.NormalAlertDialog;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.MallOrderBean;
import com.lzm.ydpt.entity.payresult.AliPayResult;
import com.lzm.ydpt.entity.payresult.PayBean;
import com.lzm.ydpt.module.mall.utils.ProductUtil;
import com.lzm.ydpt.mvp.contract.PayOrderContract;
import com.lzm.ydpt.mvp.presenterimpl.PayOrderPresenterImpl;
import com.lzm.ydpt.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 支付订单页面
 */
public class PayOrderActivity extends BaseActivity<PayOrderPresenterImpl> implements PayOrderContract.View {

    public static final String INP_PAY_ORDER = "pay_order";// 订单
    public static final String INP_PAY_JUMP_TYPE = "PAY_JUMP_TYPE";//  1：提交订单页面跳转，2：订单页面跳转

    @BindView(R.id.ntb_pay_order)
    NormalTitleBar ntb_pay_order;
    @BindView(R.id.tv_pay_money_count)
    TextView tv_pay_money_count;

    @BindView(R.id.ll_cash_pay)
    LinearLayout ll_cash_pay;
    @BindView(R.id.img_pay_wx_pro_select)
    ImageView img_pay_wx_pro_select;
    @BindView(R.id.img_pay_zfb_pro_select)
    ImageView img_pay_zfb_pro_select;

    TextView tv_order_pay_data;

    private String payType = Constants.PAY_WX; //微信支付	微信支付	weixinpay 支付宝	支付宝	alipay
    private IWXAPI wxapi;
    private MallOrderBean tempOrderbean;
    private int tempPayType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_pay_order;
    }

    @Override
    public PayOrderPresenterImpl initPreData() {
        return new PayOrderPresenterImpl(this);
    }

    @Override
    public void initView() {
        wxapi = WXAPIFactory.createWXAPI(this, Constants.WX_APIID);
        tempOrderbean = getIntent().getParcelableExtra(INP_PAY_ORDER);
        tempPayType = getIntent().getIntExtra(INP_PAY_JUMP_TYPE, 1);
        ntb_pay_order.setTitleText("提交订单");
        ntb_pay_order.setOnBackListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                showBackDialog();
            }
        });

        if (ProductUtil.pausePrice(tempOrderbean.getAmount_rmb()) > 0) {
            ll_cash_pay.setVisibility(View.VISIBLE);
            tv_order_pay_data.setText("微信支付¥" + tempOrderbean.getAmount_rmb());
            setPayMode(Constants.PAY_WX);
            if (tempOrderbean.getGoods_amount_gold() > 0) {
                tv_pay_money_count.setText(tempOrderbean.getGoods_amount_gold() + "金币+¥" + ProductUtil.formatPriceNum(tempOrderbean.getAmount_rmb()));
            } else {
                tv_pay_money_count.setText("¥" + ProductUtil.formatPriceNum(tempOrderbean.getAmount_rmb()));
            }
        } else {
            tv_pay_money_count.setText(tempOrderbean.getGoods_amount_gold() + "金币");
            ll_cash_pay.setVisibility(View.GONE);
            tv_order_pay_data.setText("立即支付");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            showBackDialog();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showBackDialog() {
        long time = System.currentTimeMillis() / 1000 - tempOrderbean.getCreated_datetime();
        int minutes = 30 - (int) time / 60;
        if (minutes > 0) {
            NormalAlertDialog normalAlertDialog = new NormalAlertDialog.Builder(mBContext)
                    .setButtonTextSize(14)
                    .setTitleVisible(true)
                    .setTitleText("确认要离开此页面")
                    .setTitleTextSize(16)
                    .setContentText("您的订单在" + minutes + "分钟内未支付将被取消,请尽快完成支付")
                    .setContentTextSize(14)
                    .setLeftButtonText("继续支付")
                    .setRightButtonText("确认离开")
                    .setContentTextColor(R.color.color_333333)
                    .setRightButtonTextColor(R.color.color_main)
                    .setLeftButtonTextColor(R.color.color_999999)
                    .setOnclickListener(new DialogOnClickListener() {
                        @Override
                        public void clickLeftButton(View view) {

                        }

                        @Override
                        public void clickRightButton(View view) {
                            Bundle bundle = new Bundle();
                            bundle.putInt(MallOrderListActivity.INP_ORDER_JUMPMODE, 1);
                            openActivity(MallOrderListActivity.class, bundle);
                            finish();
                        }
                    })
                    .build();
            normalAlertDialog.show();
        } else {
            showShortToast("订单自动取消");
            finish();
        }
    }

    @OnClick({R.id.rl_pay_wx_pro, R.id.rl_pay_zfb_pro, R.id.tv_order_pay_data})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {
            return;
        }
        switch (view.getId()) {
            case R.id.rl_pay_wx_pro:
                setPayMode(Constants.PAY_WX);
                tv_order_pay_data.setText("微信支付¥" + tempOrderbean.getAmount_rmb());
                break;
            case R.id.rl_pay_zfb_pro:
                setPayMode(Constants.PAY_ALI);
                tv_order_pay_data.setText("支付宝支付¥" + tempOrderbean.getAmount_rmb());
                break;
            case R.id.tv_order_pay_data:
                onPayAllData();
                break;
        }
    }

    private void onPayAllData() {
        startProgressDialog();
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("order_id", tempOrderbean.getOrder_id());
        formBodys.add("request_type", tempPayType);
        formBodys.add("payment_platfrom", payType);
        mPresenter.onPayOrder(formBodys.build());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int type = intent.getIntExtra(WXPayEntryActivity.INP_WX_PAY_TYPE, -1);
        if (type != -1) {
            Bundle bundle = new Bundle();
            bundle.putInt(Constants.INP_ORDER_STATUS, type);
            bundle.putInt(Constants.INP_ORDER_JUMP_TYPE, tempPayType);
            bundle.putParcelable(Constants.INP_ORDER_BEAN, tempOrderbean);
            openActivity(OrderPayStatusActivity.class, bundle);
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isOPPO() && WXPayEntryActivity.WXYUANSHENGPEI != -1) {
            WXPayEntryActivity.WXYUANSHENGPEI = -1;
            Bundle bundle = new Bundle();
            bundle.putInt(Constants.INP_ORDER_STATUS, WXPayEntryActivity.WXYUANSHENGPEI);
            bundle.putInt(Constants.INP_ORDER_JUMP_TYPE, tempPayType);
            bundle.putParcelable(Constants.INP_ORDER_BEAN, tempOrderbean);
            openActivity(OrderPayStatusActivity.class, bundle);
            finish();
        }
    }

    private boolean isOPPO() {
        String manufacturer = Build.MANUFACTURER;
        return "OPPO".equalsIgnoreCase(manufacturer);
    }

    public void wxPayReq(PayBean weixinPay) {
        WXPayEntryActivity.PAYTYPE = 1;
        PayReq req = new PayReq();
        req.appId = Constants.WX_APIID;
        req.partnerId = weixinPay.getPartnerid();
        req.prepayId = weixinPay.getPrepayid();
        req.packageValue = weixinPay.getWx_package();
        req.nonceStr = weixinPay.getNoncestr();
        req.timeStamp = weixinPay.getTimestamp();
        req.sign = weixinPay.getSign();
        wxapi.registerApp(Constants.WX_APIID);
        wxapi.sendReq(req);
    }

    private void setPayMode(String mode) {
        this.payType = mode;
        img_pay_wx_pro_select.setSelected(mode.equals(Constants.PAY_WX));
        img_pay_zfb_pro_select.setSelected(mode.equals(Constants.PAY_ALI));
    }

    private static final int SDK_PAY_FLAG = 1;

    public void aliPayReq(String orderInfo) {
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    @SuppressWarnings("unchecked")
                    AliPayResult payResult = new AliPayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    Bundle bundle = new Bundle();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        bundle.putInt(Constants.INP_ORDER_STATUS, 1);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        bundle.putInt(Constants.INP_ORDER_STATUS, 0);
                    }
                    bundle.putInt(Constants.INP_ORDER_JUMP_TYPE, tempPayType);
                    bundle.putParcelable(Constants.INP_ORDER_BEAN, tempOrderbean);
                    openActivity(OrderPayStatusActivity.class, bundle);
                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onPayOrder(PayBean payBean) {
        stopProgressDialog();
        if (payBean != null) {
            if (payType.equals(Constants.PAY_WX)) {
                wxPayReq(payBean);
            } else if (payType.equals(Constants.PAY_ALI)) {
                if (!TextUtils.isEmpty(payBean.getAlipay_str())) {
                    aliPayReq(payBean.getAlipay_str());
                } else {
                    showShortToast("支付宝订单未拿到,请重新请求");
                }
            }
        }
    }

    @Override
    public void showMessage(String message, String method) {
        stopProgressDialog();
        showShortToast(message);
        if (method.equals("payCoinData")) {
            Bundle bundle = new Bundle();
            bundle.putInt(Constants.INP_ORDER_STATUS, 0);
            bundle.putInt(Constants.INP_ORDER_JUMP_TYPE, tempPayType);
            bundle.putParcelable(Constants.INP_ORDER_BEAN, tempOrderbean);
            openActivity(OrderPayStatusActivity.class, bundle);
            finish();
        }
    }

    @Override
    public void showErrorView(String msg) {

    }
}